<template>
  <div class="workspace">
    <div class="workspace-container">
      <!-- 左侧文章列表 -->
      <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
        <div class="sidebar-header">
          <!-- Logo和用户中心 -->
          <div class="header-top" v-if="!sidebarCollapsed">
            <div class="logo-section">
              <i class="el-icon-edit-outline logo-icon"></i>
              <span class="logo-text">成章</span>
            </div>
            <div class="user-section">
              <el-dropdown trigger="click">
                <span class="user-info">
                  <i class="el-icon-user-solid"></i>
                  <span>用户中心</span>
                  <i class="el-icon-arrow-down"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="exportData">
                    <i class="el-icon-download"></i>
                    导出数据
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="importData">
                    <i class="el-icon-upload2"></i>
                    导入数据
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="clearData">
                    <i class="el-icon-delete"></i>
                    清空数据
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
        
        <div class="sidebar-content" v-if="!sidebarCollapsed">
          <!-- 搜索和筛选 -->
          <div class="search-section">
            <!-- 搜索框占据一行 -->
            <div class="search-row">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索文章..."
                prefix-icon="el-icon-search"
                clearable
                @input="handleSearch"
                class="search-input"
                size="mini"
              ></el-input>
            </div>
            
            <!-- 筛选器占据一行 -->
            <div class="filter-row">
              <el-select v-model="statusFilter" placeholder="状态" size="mini" @change="handleSearch" class="status-filter">
                <el-option label="全部" value="all"></el-option>
                <el-option label="草稿" value="draft"></el-option>
                <el-option label="已发布" value="published"></el-option>
                <el-option label="已归档" value="archived"></el-option>
              </el-select>
              
              <collection-filter
                v-model="collectionFilter"
                @change="handleCollectionFilter"
                class="collection-filter"
              ></collection-filter>
            </div>
          </div>
          
          <!-- 新建文章按钮 -->
          <div class="action-section">
            <el-button 
              type="primary" 
              icon="el-icon-plus" 
              @click="createNewArticle"
              class="new-article-btn"
              size="mini"
            >
              新建文章
            </el-button>
          </div>
          
          <!-- 文章列表 -->
          <div class="article-list">
            <div 
              v-for="article in filteredArticles" 
              :key="article.id"
              class="article-item"
              :class="{ active: currentArticleId === article.id }"
              @click="selectArticle(article)"
            >
              <div class="article-header">
                <div class="article-title-section">
                  <h4 class="article-title">{{ article.title || '无标题' }}</h4>
                  <div class="article-meta">
                    <span class="status-badge" :class="article.status">
                      {{ article.status === 'published' ? '发布' : article.status === 'archived' ? '归档' : '草稿' }}
                    </span>
                    <span v-if="article.collection" 
                          class="collection-badge"
                          :style="{ borderColor: getCollectionColor(article.collection), color: getCollectionColor(article.collection) }">
                      {{ getCollectionName(article.collection) }}
                    </span>
                    <span v-else class="collection-badge uncategorized">
                      未分类
                    </span>
                    <span class="article-date">{{ formatDate(article.updatedAt) }}</span>
                  </div>
                </div>
                <div class="article-actions">
                  <el-button
                    type="text"
                    icon="el-icon-copy-document"
                    size="mini"
                    @click.stop="handleArticleAction({ action: 'copy', article })"
                    title="复制"
                  />
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="mini"
                    @click.stop="handleArticleAction({ action: 'delete', article })"
                    title="删除"
                  />
                </div>
              </div>
            </div>
            
            <!-- 空状态 -->
            <div v-if="filteredArticles.length === 0" class="empty-state">
              <i class="el-icon-document-add"></i>
              <p>{{ searchKeyword ? '未找到相关文章' : '还没有文章，开始创作吧！' }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧编辑器 -->
      <div class="editor-container">
        <div v-if="currentArticle" class="editor-wrapper">
          <!-- 编辑器工具栏 -->
          <div class="editor-toolbar">
            <div class="toolbar-left">
              <el-input
                v-model="currentArticle.title"
                placeholder="请输入文章标题"
                class="title-input"
                @input="handleTitleChange"
                size="medium"
              ></el-input>
            </div>
            
            <div class="toolbar-right">
              <!-- 自动保存状态提示 -->
              <span v-if="autoSaveStatus" class="auto-save-status">
                <i class="el-icon-check"></i>
                {{ autoSaveStatus }}
              </span>
              
              <el-button-group>
                <el-button 
                  :type="editMode === 'edit' ? 'primary' : 'default'"
                  @click="setEditMode('edit')"
                  size="mini"
                >
                  编辑
                </el-button>
                <el-button 
                  :type="editMode === 'split' ? 'primary' : 'default'"
                  @click="setEditMode('split')"
                  size="mini"
                >
                  分栏
                </el-button>
                <el-button 
                  :type="editMode === 'preview' ? 'primary' : 'default'"
                  @click="setEditMode('preview')"
                  size="mini"
                >
                  预览
                </el-button>
              </el-button-group>
              
              <el-button 
                @click="toggleFullscreen"
                :icon="isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"
                size="mini"
              ></el-button>
              
              <collection-selector
                v-model="currentArticle.collection"
                @change="handleCollectionChange"
                placeholder="选择合集"
                class="collection-selector"
              ></collection-selector>
              
              <el-button 
                type="success"
                @click="saveArticle"
                :loading="saving"
                size="mini"
              >
                {{ saving ? '保存中...' : '保存' }}
              </el-button>
              
              <el-dropdown @command="handleStatusChange">
                <el-button size="mini">
                  {{ currentArticle.status === 'published' ? '已发布' : '草稿' }}
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="draft">保存为草稿</el-dropdown-item>
                  <el-dropdown-item command="published">发布文章</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          
          <!-- 编辑器内容区 -->
          <div class="editor-content" :class="{ fullscreen: isFullscreen }">
            <mavon-editor
              ref="editor"
              v-model="currentArticle.content"
              :toolbars="toolbars"
              :ishljs="true"
              :external-link="false"
              :scroll-style="true"
              :box-shadow="false"
              :tab-size="2"
              :placeholder="'开始写作...'"
              @change="handleContentChange"
              @imgAdd="handleImageUpload"
              @imgDel="handleImageDelete"
              @drop="handleDrop"
              @paste="handlePaste"
              class="markdown-editor"
            />
          </div>
        </div>
        
        <!-- 未选择文章时的欢迎页面 -->
        <div v-else class="welcome-screen">
          <div class="welcome-content">
            <i class="el-icon-edit-outline welcome-icon"></i>
            <h2>欢迎使用成章编辑器</h2>
            <p>选择左侧文章开始编辑，或创建新文章开始写作</p>
            <el-button type="primary" @click="createNewArticle" icon="el-icon-plus">
              创建新文章
            </el-button>
          </div>
        </div>
      </div>
      <!-- 右侧边栏 -->
      <right-sidebar
        @copy-wechat="handleWechatCopy"
        @copy-zhihu="handleZhihuCopy"
        @settings-changed="handleSettingsChanged"
        @style-changed="handleStyleChanged"
        @collection-changed="handleCollectionChanged"
      />
    </div>
    
    <!-- 文件导入隐藏input -->
    <input
      ref="fileInput"
      type="file"
      accept=".json"
      style="display: none"
      @change="handleFileImport"
    >
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'
import { debounce } from '@/utils/helpers'
import RightSidebar from '@/components/common/RightSidebar'
import CollectionFilter from '@/components/common/CollectionFilter'
import CollectionSelector from '@/components/common/CollectionSelector'
import { imageApi } from '@/api/images'

export default {
  name: 'WorkspacePage',
  
  components: {
    RightSidebar,
    CollectionFilter,
    CollectionSelector
  },
  
  data() {
    return {
      sidebarCollapsed: false,
      searchKeyword: '',
      statusFilter: 'all',
      collectionFilter: 'all', // 新增：合集筛选
      filteredArticles: [],
      currentArticleId: null,
      currentArticle: null,
      editMode: 'split', // edit, split, preview
      isFullscreen: false,
      saving: false,
      autoSaveTimer: null,
      autoSaveStatus: '', // 自动保存状态提示
      // 图片上传相关状态
      uploading: false,
      uploadProgress: 0,
      uploadedImages: [],
      toolbars: {
        bold: true,
        italic: true,
        header: true,
        underline: true,
        strikethrough: true,
        mark: true,
        superscript: true,
        subscript: true,
        quote: true,
        ol: true,
        ul: true,
        link: true,
        imagelink: true,
        code: true,
        table: true,
        fullscreen: true,
        readmodel: true,
        htmlcode: true,
        help: true,
        undo: true,
        redo: true,
        trash: true,
        save: true,
        navigation: true,
        alignleft: true,
        aligncenter: true,
        alignright: true,
        subfield: true,
        preview: true
      }
    }
  },
  
  computed: {
    ...mapState('articles', ['articles', 'collections']),
    ...mapState('editor', ['currentId'])
  },
  
  async created() {
    await this.loadArticles()
    await this.loadCollections() // 新增：加载合集数据
    this.filterArticles()
    
    // 如果有路由参数中的文章ID，自动选择该文章
    const articleId = this.$route.params.id
    if (articleId) {
      const article = this.articles.find(a => a.id === articleId)
      if (article) {
        this.selectArticle(article)
      }
    }
    
    // 设置自动保存
    this.setupAutoSave()
  },
  
  beforeDestroy() {
    if (this.autoSaveTimer) {
      clearInterval(this.autoSaveTimer)
    }
  },
  
  methods: {
    ...mapActions('articles', ['loadArticles', 'createArticle', 'updateArticle', 'deleteArticle', 'loadCollections']),
    ...mapMutations('editor', ['LOAD_ARTICLE']),
    
    // 切换侧边栏
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
    },
    
    // 导出数据
    async exportData() {
      try {
        this.$message({
          message: '正在导出数据...',
          type: 'info'
        })
        
        const articles = this.$store.state.articles.articles
        
        const exportData = {
          articles,
          exportTime: new Date().toISOString(),
          version: '1.0'
        }
        
        const filename = `成章数据备份_${new Date().toISOString().split('T')[0]}.json`
        const { downloadFile } = await import('@/utils/helpers')
        downloadFile(JSON.stringify(exportData, null, 2), filename, 'application/json')
        
        this.$message({
          message: '数据导出成功',
          type: 'success'
        })
      } catch (error) {
        console.error('导出数据失败:', error)
        this.$message({
          message: '导出数据失败',
          type: 'error'
        })
      }
    },
    
    // 导入数据
    importData() {
      this.$refs.fileInput.click()
    },
    
    // 处理文件导入
    async handleFileImport(event) {
      const file = event.target.files[0]
      if (!file) return
      
      try {
        this.$message({
          message: '正在导入数据...',
          type: 'info'
        })
        
        const { readFileContent } = await import('@/utils/helpers')
        const content = await readFileContent(file)
        const data = JSON.parse(content)
        
        // 验证数据格式
        if (!data.articles || !Array.isArray(data.articles)) {
          throw new Error('无效的数据格式')
        }
        
        // 确认导入
        const result = await this.$confirm(
          `确定要导入 ${data.articles.length} 篇文章吗？这将覆盖现有数据。`,
          '确认导入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          // 导入文章
          this.$store.commit('articles/SET_ARTICLES', data.articles)
          
          this.$message({
            message: '数据导入成功',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('导入数据失败:', error)
        this.$message({
          message: '导入数据失败：' + error.message,
          type: 'error'
        })
      } finally {
        // 清空文件输入
        event.target.value = ''
      }
    },
    
    // 清空数据
    async clearData() {
      try {
        const result = await this.$confirm(
          '确定要清空所有数据吗？此操作不可恢复。',
          '确认清空',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          // 清空文章数据
          this.$store.commit('articles/SET_ARTICLES', [])
          
          // 重置编辑器
          this.$store.dispatch('editor/resetEditor')
          
          this.$message({
            message: '数据清空成功',
            type: 'success'
          })
        }
      } catch (error) {
        // 用户取消操作
      }
    },
    
    // 搜索处理
    handleSearch: debounce(function() {
      this.filterArticles()
    }, 300),
    
    // 过滤文章
    filterArticles() {
      let filtered = [...this.articles]
      
      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(article => 
          article.title.toLowerCase().includes(keyword) ||
          article.content.toLowerCase().includes(keyword) ||
          (article.summary && article.summary.toLowerCase().includes(keyword))
        )
      }
      
      // 状态过滤
      if (this.statusFilter !== 'all') {
        filtered = filtered.filter(article => article.status === this.statusFilter)
      }
      
      // 新增：合集过滤
      if (this.collectionFilter !== 'all') {
        if (this.collectionFilter === '') {
          // 筛选“未分类”
          filtered = filtered.filter(article => !article.collection || article.collection === '')
        } else {
          // 筛选具体合集
          filtered = filtered.filter(article => article.collection === this.collectionFilter)
        }
      }
      
      // 按更新时间排序
      filtered.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
      
      this.filteredArticles = filtered
    },
    
    // 选择文章
    selectArticle(article) {
      this.currentArticleId = article.id
      this.currentArticle = { ...article }
      this.LOAD_ARTICLE(article)
      
      // 更新路由
      if (this.$route.params.id !== article.id) {
        this.$router.replace(`/workspace/${article.id}`)
      }
    },
    
    // 创建新文章
    async createNewArticle() {
      try {
        const newArticle = await this.createArticle({
          title: '新文章',
          content: '',
          status: 'draft',
          collection: '' // 默认为未分类
        })
        
        await this.loadArticles()
        this.filterArticles()
        this.selectArticle(newArticle)
        
        this.$message.success('新文章创建成功')
      } catch (error) {
        this.$message.error('创建文章失败')
      }
    },
    
    // 新增：合集筛选处理
    handleCollectionFilter(collectionId) {
      this.collectionFilter = collectionId
      this.filterArticles()
    },
    
    // 新增：合集选择处理
    handleCollectionChange(collectionId) {
      if (this.currentArticle) {
        this.currentArticle.collection = collectionId
        // 自动保存文章
        this.debouncedSave()
      }
    },
    
    // 新增：获取合集名称
    getCollectionName(collectionId) {
      return this.$store.getters['articles/getCollectionName'](collectionId)
    },
    
    // 新增：获取合集颜色
    getCollectionColor(collectionId) {
      return this.$store.getters['articles/getCollectionColor'](collectionId)
    },
    
    // 文章操作处理
    async handleArticleAction({ action, article }) {
      switch (action) {
        case 'copy':
          await this.copyArticle(article)
          break
        case 'delete':
          await this.confirmDeleteArticle(article)
          break
      }
    },
    
    // 复制文章
    async copyArticle(article) {
      try {
        const copiedArticle = await this.createArticle({
          title: `${article.title} - 副本`,
          content: article.content,
          status: 'draft',
          tags: [...article.tags]
        })
        
        await this.loadArticles()
        this.filterArticles()
        this.selectArticle(copiedArticle)
        
        this.$message.success('文章复制成功')
      } catch (error) {
        this.$message.error('复制文章失败')
      }
    },
    
    // 确认删除文章
    async confirmDeleteArticle(article) {
      try {
        await this.$confirm(
          `确定要删除文章「${article.title}」吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await this.deleteArticle(article.id)
        await this.loadArticles()
        this.filterArticles()
        
        // 如果删除的是当前文章，清空编辑器
        if (this.currentArticleId === article.id) {
          this.currentArticle = null
          this.currentArticleId = null
          this.$router.replace('/workspace')
        }
        
        this.$message.success('文章删除成功')
      } catch (error) {
        // 用户取消删除
      }
    },
    
    // 标题变化处理
    handleTitleChange: debounce(function() {
      this.saveArticle()
    }, 1000),
    
    // 内容变化处理
    handleContentChange: debounce(function() {
      this.saveArticle()
    }, 2000),
    
    // 切换编辑模式
    setEditMode(mode) {
      this.editMode = mode
    },
    
    // 处理样式变更
    handleStyleChanged(styleContent) {
      // 创建或更新样式标签
      let styleEl = document.getElementById('custom-article-style')
      if (!styleEl) {
        styleEl = document.createElement('style')
        styleEl.id = 'custom-article-style'
        document.head.appendChild(styleEl)
      }
      
      styleEl.innerHTML = styleContent
    },
    
    // 切换全屏
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
    },
    
    // 保存文章
    async saveArticle() {
      if (!this.currentArticle || this.saving) return
      
      try {
        this.saving = true
        
        await this.updateArticle({
          id: this.currentArticle.id,
          data: this.currentArticle
        })
        
        await this.loadArticles()
        this.filterArticles()
        
        // 更新当前文章数据
        const updatedArticle = this.articles.find(a => a.id === this.currentArticle.id)
        if (updatedArticle) {
          this.currentArticle = { ...updatedArticle }
        }
        
        // 显示自动保存状态
        this.autoSaveStatus = '保存成功'
        // 3秒后清除状态提示
        setTimeout(() => {
          this.autoSaveStatus = ''
        }, 3000)
        
      } catch (error) {
        console.error('保存文章失败:', error)
        this.$message.error('保存失败: ' + (error.message || '未知错误'))
      } finally {
        this.saving = false
      }
    },
    
    // 状态变化处理
    async handleStatusChange(status) {
      if (!this.currentArticle) return
      
      this.currentArticle.status = status
      await this.saveArticle()
      
      this.$message.success(
        status === 'published' ? '文章已发布' : '文章已保存为草稿'
      )
    },
    
    // 图片上传处理
    async handleImageUpload(pos, file) {
      try {
        this.uploading = true
        this.uploadProgress = 0
        
        // 显示上传进度提示
        const loadingMessage = this.$message({
          message: '正在上传图片...',
          type: 'info',
          duration: 0,
          showClose: true
        })
        
        // 上传图片
        const result = await imageApi.upload(file, {
          articleId: this.currentArticle?.id,
          onProgress: (percent) => {
            this.uploadProgress = percent
            loadingMessage.message = `正在上传图片... ${percent}%`
          }
        })
        
        // 关闭加载提示
        loadingMessage.close()
        
        // 获取图片URL
        const imageUrl = imageApi.getPreviewUrl(result.filePath)
        
        // 将图片插入到编辑器
        this.$refs.editor.$img2Url(pos, imageUrl)
        
        // 记录上传的图片
        this.uploadedImages.push({
          id: result.id,
          url: imageUrl,
          originalName: file.name,
          size: file.size
        })
        
        this.$message.success('图片上传成功')
        
      } catch (error) {
        console.error('图片上传失败:', error)
        this.$message.error('图片上传失败: ' + error.message)
      } finally {
        this.uploading = false
        this.uploadProgress = 0
      }
    },
    
    // 图片删除处理
    async handleImageDelete(filename) {
      try {
        // 从上传记录中找到对应的图片
        const imageRecord = this.uploadedImages.find(img => img.url.includes(filename))
        
        if (imageRecord) {
          // 删除服务器上的图片
          await imageApi.delete(imageRecord.id)
          
          // 从记录中移除
          const index = this.uploadedImages.findIndex(img => img.id === imageRecord.id)
          if (index > -1) {
            this.uploadedImages.splice(index, 1)
          }
          
          this.$message.success('图片删除成功')
        }
      } catch (error) {
        console.error('图片删除失败:', error)
        this.$message.error('图片删除失败: ' + error.message)
      }
    },
    
    // 处理拖拽上传
    async handleDrop(event) {
      event.preventDefault()
      
      const files = Array.from(event.dataTransfer.files)
      const imageFiles = files.filter(file => file.type.startsWith('image/'))
      
      if (imageFiles.length === 0) {
        this.$message.warning('请拖拽图片文件')
        return
      }
      
      // 批量上传图片
      await this.batchUploadImages(imageFiles)
    },
    
    // 处理粘贴上传
    async handlePaste(event) {
      const items = Array.from(event.clipboardData.items)
      const imageItems = items.filter(item => item.type.startsWith('image/'))
      
      if (imageItems.length === 0) {
        return // 没有图片，继续默认粘贴行为
      }
      
      event.preventDefault()
      
      for (const item of imageItems) {
        const file = item.getAsFile()
        if (file) {
          // 为粘贴的图片生成一个位置标识
          const pos = Date.now().toString()
          await this.handleImageUpload(pos, file)
        }
      }
    },
    
    // 批量上传图片
    async batchUploadImages(files) {
      try {
        this.uploading = true
        
        const results = await imageApi.batchUpload(files, {
          articleId: this.currentArticle?.id,
          onProgress: (overallProgress, current, total) => {
            this.uploadProgress = overallProgress
            this.$message({
              message: `正在上传第 ${current}/${total} 张图片... ${overallProgress}%`,
              type: 'info',
              duration: 1000
            })
          },
          onSingleComplete: (result, current) => {
            // 将成功上传的图片插入到编辑器
            const imageUrl = imageApi.getPreviewUrl(result.filePath)
            const pos = Date.now().toString() + current
            this.$refs.editor.$img2Url(pos, imageUrl)
            
            // 记录上传的图片
            this.uploadedImages.push({
              id: result.id,
              url: imageUrl,
              originalName: result.originalName,
              size: result.fileSize
            })
          }
        })
        
        const successCount = results.filter(r => r.success).length
        const failCount = results.filter(r => !r.success).length
        
        if (successCount > 0) {
          this.$message.success(`成功上传 ${successCount} 张图片`)
        }
        
        if (failCount > 0) {
          this.$message.error(`${failCount} 张图片上传失败`)
        }
        
      } catch (error) {
        console.error('批量上传失败:', error)
        this.$message.error('批量上传失败: ' + error.message)
      } finally {
        this.uploading = false
        this.uploadProgress = 0
      }
    },
    
    // 设置自动保存
    setupAutoSave() {
      this.autoSaveTimer = setInterval(() => {
        if (this.currentArticle && !this.saving) {
          this.saveArticle()
        }
      }, 300000) // 每30秒自动保存
    },
    
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return date.toLocaleDateString()
      }
    },
    
    // 复制到公众号
    async handleWechatCopy() {
      try {
        if (!this.currentArticle || !this.currentArticle.content) {
          this.$message.warning('没有可复制的内容')
          return
        }
        
        // 获取渲染后的HTML
        const markdownHtml = this.$refs.editor?.d_render || ''
        
        if (markdownHtml) {
          // 添加公众号样式
          const wechatHtml = this.formatForWechat(markdownHtml)
          
          // 使用现代的Clipboard API复制富文本
          if (navigator.clipboard && window.ClipboardItem) {
            const blob = new Blob([wechatHtml], { type: 'text/html' })
            const textBlob = new Blob([this.stripHtml(wechatHtml)], { type: 'text/plain' })
            
            const clipboardItem = new ClipboardItem({
              'text/html': blob,
              'text/plain': textBlob
            })
            
            await navigator.clipboard.write([clipboardItem])
            this.$message.success('公众号格式已复制到剪贴板')
          } else {
            // 降级到传统方法
            this.fallbackCopy(wechatHtml)
          }
        } else {
          this.$message.warning('渲染内容为空')
        }
      } catch (error) {
        console.error('复制失败:', error)
        this.$message.error('复制失败，请手动复制')
      }
    },
    
    // 复制到知乎
    async handleZhihuCopy() {
      try {
        if (!this.currentArticle || !this.currentArticle.content) {
          this.$message.warning('没有可复制的内容')
          return
        }
        
        // 获取渲染后的HTML
        const markdownHtml = this.$refs.editor?.d_render || ''
        
        if (markdownHtml) {
          // 添加知乎样式
          const zhihuHtml = this.formatForZhihu(markdownHtml)
          
          // 使用现代的Clipboard API复制富文本
          if (navigator.clipboard && window.ClipboardItem) {
            const blob = new Blob([zhihuHtml], { type: 'text/html' })
            const textBlob = new Blob([this.stripHtml(zhihuHtml)], { type: 'text/plain' })
            
            const clipboardItem = new ClipboardItem({
              'text/html': blob,
              'text/plain': textBlob
            })
            
            await navigator.clipboard.write([clipboardItem])
            this.$message.success('知乎格式已复制到剪贴板')
          } else {
            // 降级到传统方法
            this.fallbackCopy(zhihuHtml)
          }
        } else {
          this.$message.warning('渲染内容为空')
        }
      } catch (error) {
        console.error('复制失败:', error)
        this.$message.error('复制失败，请手动复制')
      }
    },
    
    // 降级复制方法
    fallbackCopy(html) {
      const tempDiv = document.createElement('div')
      tempDiv.contentEditable = true
      tempDiv.innerHTML = html
      tempDiv.style.position = 'fixed'
      tempDiv.style.left = '-9999px'
      document.body.appendChild(tempDiv)
      
      const selection = window.getSelection()
      const range = document.createRange()
      range.selectNodeContents(tempDiv)
      selection.removeAllRanges()
      selection.addRange(range)
      
      try {
        document.execCommand('copy')
        this.$message.success('格式已复制到剪贴板')
      } catch (err) {
        navigator.clipboard.writeText(this.stripHtml(html))
          .then(() => this.$message.success('文本内容已复制到剪贴板'))
          .catch(() => this.$message.error('复制失败，请手动复制'))
      }
      
      selection.removeAllRanges()
      document.body.removeChild(tempDiv)
    },
    
    // 去除HTML标签获取纯文本
    stripHtml(html) {
      const tmp = document.createElement('div')
      tmp.innerHTML = html
      return tmp.textContent || tmp.innerText || ''
    },
    
    // 格式化为公众号样式
    formatForWechat(html) {
      // 公众号样式模板 - 针对公众号编辑器优化
      return `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.75; color: #333; word-wrap: break-word;">
  ${this.processHtmlForWechat(html)}
</div>
      `
    },
    
    // 格式化为知乎样式
    formatForZhihu(html) {
      // 知乎样式模板 - 针对知乎编辑器优化
      return `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; font-size: 15px; line-height: 1.7; color: #121212; word-wrap: break-word;">
  ${this.processHtmlForZhihu(html)}
</div>
      `
    },
    
    // 处理HTML内容适配公众号
    processHtmlForWechat(html) {
      // 替换样式以适配公众号
      return html
        .replace(/<h1/g, '<h1 style="font-size: 24px; font-weight: bold; margin: 24px 0 16px 0; color: #000;"')
        .replace(/<h2/g, '<h2 style="font-size: 22px; font-weight: bold; margin: 24px 0 16px 0; color: #000;"')
        .replace(/<h3/g, '<h3 style="font-size: 20px; font-weight: bold; margin: 24px 0 16px 0; color: #000;"')
        .replace(/<p>/g, '<p style="margin: 0 0 16px 0; text-align: justify; text-indent: 2em;">')
        .replace(/<blockquote/g, '<blockquote style="border-left: 4px solid #07c160; padding-left: 16px; margin: 16px 0; color: #666; font-style: italic;"')
        .replace(/<code>/g, '<code style="background-color: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-family: \'Monaco\', \'Menlo\', \'Consolas\', monospace; font-size: 14px;">')
        .replace(/<pre>/g, '<pre style="background-color: #f8f8f8; padding: 16px; border-radius: 4px; overflow-x: auto; margin: 16px 0;">')
        .replace(/<img/g, '<img style="max-width: 100%; height: auto; display: block; margin: 16px auto;"')
    },
    
    // 处理HTML内容适配知乎
    processHtmlForZhihu(html) {
      // 替换样式以适配知乎
      return html
        .replace(/<h1/g, '<h1 style="font-size: 26px; font-weight: 600; margin: 24px 0 16px 0; color: #1a1a1a;"')
        .replace(/<h2/g, '<h2 style="font-size: 24px; font-weight: 600; margin: 24px 0 16px 0; color: #1a1a1a;"')
        .replace(/<h3/g, '<h3 style="font-size: 22px; font-weight: 600; margin: 24px 0 16px 0; color: #1a1a1a;"')
        .replace(/<p>/g, '<p style="margin: 0 0 16px 0; text-align: justify;">')
        .replace(/<blockquote/g, '<blockquote style="border-left: 3px solid #0066ff; padding-left: 16px; margin: 16px 0; color: #646464; background-color: #f9f9f9;"')
        .replace(/<code>/g, '<code style="background-color: #f1f1f1; padding: 2px 6px; border-radius: 3px; font-family: \'Monaco\', \'Menlo\', \'Consolas\', monospace; font-size: 14px;">')
        .replace(/<pre>/g, '<pre style="background-color: #f6f6f6; padding: 16px; border-radius: 4px; overflow-x: auto; margin: 16px 0;">')
        .replace(/<img/g, '<img style="max-width: 100%; height: auto; display: block; margin: 16px auto; border-radius: 4px;"')
    },
    
    // 处理设置变更
    handleSettingsChanged(settings) {
      // 应用设置变更
      document.documentElement.style.setProperty('--editor-font-size', `${settings.fontSize}px`)

      // 可以在这里添加更多设置的应用逻辑
      console.log('设置已更新:', settings)
    },

    // 处理合集变化
    async handleCollectionChanged() {
      // 重新加载合集数据
      await this.loadCollections()
      // 重新过滤文章列表
      this.filterArticles()
    }
  },
  
  watch: {
    articles() {
      this.filterArticles()
    }
  }
}
</script>

<style lang="scss" scoped>
.workspace {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  
  .workspace-container {
    display: flex;
    height: 100%;
  }
}

.sidebar {
  width: 260px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(232, 232, 232, 0.8);
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  
  &.collapsed {
    width: 40px;
  }
  
  .sidebar-header {
    padding: 12px 16px;
    border-bottom: 1px solid rgba(240, 240, 240, 0.8);
    display: flex;
    flex-direction: column;
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    
    .header-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      
      .logo-section {
        display: flex;
        align-items: center;
        
        .logo-icon {
          font-size: 20px;
          color: #409eff;
          margin-right: 6px;
        }
        
        .logo-text {
          font-size: 16px;
          font-weight: 600;
          background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }
      
      .user-section {
        .user-info {
          display: flex;
          align-items: center;
          cursor: pointer;
          padding: 4px 8px;
          border-radius: 6px;
          transition: background-color 0.3s;
          font-size: 12px;
          color: #666;
          
          &:hover {
            background-color: #f0f0f0;
          }
          
          i {
            margin: 0 2px;
            font-size: 12px;
          }
          
          span {
            font-size: 12px;
          }
        }
      }
    }
    
    .collapse-btn {
      padding: 4px;
      transition: all 0.3s ease;
      align-self: flex-end;
      
      &:hover {
        transform: scale(1.1);
      }
    }
  }
  
  .sidebar-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .search-section {
    padding: 12px 16px;
    border-bottom: 1px solid rgba(240, 240, 240, 0.8);
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    
    .search-row {
      margin-bottom: 8px;
      
      .search-input {
        width: 100%;
        
        ::v-deep .el-input__inner {
          border-radius: 8px;
          border: 1px solid #e8e8e8;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }
      }
    }
    
    .filter-row {
      display: flex;
      gap: 8px;
      align-items: center;
      
      .status-filter {
        width: 80px;
        
        ::v-deep .el-input__inner {
          border-radius: 8px;
          border: 1px solid #e8e8e8;
          transition: all 0.3s ease;
        }
      }
      
      .collection-filter {
        width: 90px;
      }
    }
    
    // 保持兼容性
    .search-filter-row {
      display: flex;
      gap: 10px;
      align-items: center;
      
      .search-input {
        flex: 1;
        
        ::v-deep .el-input__inner {
          border-radius: 8px;
          border: 1px solid #e8e8e8;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }
      }
      
      .status-filter {
        width: 85px;
        
        ::v-deep .el-input__inner {
          border-radius: 8px;
          border: 1px solid #e8e8e8;
          transition: all 0.3s ease;
        }
      }
    }
  }
  
  .action-section {
    padding: 12px 16px;
    border-bottom: 1px solid rgba(240, 240, 240, 0.8);
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    
    .new-article-btn {
      width: 100%;
      border-radius: 8px;
      background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
      border: none;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
  
  .article-list {
    flex: 1;
    overflow-y: auto;
    padding: 0;
    background: #fff;
    
    .article-item {
      padding: 12px 16px;
      margin-bottom: 2px;
      cursor: pointer;
      transition: all 0.2s ease;
      background: #fff;
      border-radius: 0;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &.active {
        background: #e6f4ff;
        border-left: 3px solid #409eff;
        padding-left: 13px;
      }
      
      .article-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .article-title-section {
          flex: 1;
          
          .article-title {
            margin: 0 0 4px 0;
            font-size: 14px;
            font-weight: 600;
            color: #333;
            line-height: 1.4;
            word-wrap: break-word;
            word-break: break-all;
            white-space: normal;
          }
          
          .article-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 11px;
            
            .status-badge {
              padding: 2px 6px;
              border-radius: 10px;
              font-size: 10px;
              font-weight: 500;
              
              &.draft {
                background: #f5f5f5;
                color: #666;
              }
              
              &.published {
                background: #e8f5e8;
                color: #52c41a;
              }
              
              &.archived {
                background: #fff2e8;
                color: #fa8c16;
              }
            }
            
            .collection-badge {
              padding: 2px 6px;
              border-radius: 8px;
              font-size: 10px;
              font-weight: 400;
              border: 1px solid;
              background: transparent;
              
              &.uncategorized {
                border-color: #C0C4CC;
                color: #C0C4CC;
              }
            }
            
            .article-date {
              color: #999;
            }
          }
        }
        
        .article-actions {
          display: flex;
          gap: 4px;
          opacity: 0;
          transition: opacity 0.2s;
          margin-left: 8px;
        }
      }
      
      &:hover .article-actions {
        opacity: 1;
      }
    }
    
    .empty-state {
      text-align: center;
      padding: 40px 20px;
      color: #999;
      
      i {
        font-size: 48px;
        margin-bottom: 16px;
        display: block;
      }
    }
  }
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  
  .editor-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .editor-toolbar {
    padding: 8px 16px;
    border-bottom: 1px solid rgba(232, 232, 232, 0.8);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    .toolbar-left {
      flex: 1;
      margin-right: 16px;
      
      .title-input {
        max-width: 400px;
        
        ::v-deep .el-input__inner {
          border: none;
          font-size: 18px;
          font-weight: 600;
          padding: 8px 0;
          padding-left: 0;
          height: 40px;
          background: transparent;
          color: #333;
          
          &:focus {
            border-bottom: 2px solid #409eff;
            box-shadow: 0 2px 0 0 rgba(64, 158, 255, 0.1);
          }
          
          &::placeholder {
            color: #bbb;
            font-weight: 400;
          }
        }
      }
    }
    
    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 6px;
      
      .auto-save-status {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #67c23a;
        font-size: 12px;
        margin-right: 8px;
        padding: 2px 8px;
        background: rgba(103, 194, 58, 0.1);
        border-radius: 12px;
        animation: fadeIn 0.3s ease-in-out;
        
        i {
          font-size: 12px;
        }
      }
    }
  }
  
  .editor-content {
    flex: 1;
    overflow: hidden;
    
    &.fullscreen {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 9999;
      background: #fff;
    }
    
    .markdown-editor {
      height: 100%;
      border-radius: 0 0 8px 8px;
      overflow: hidden;
      
      ::v-deep .v-note-wrapper {
        border: none;
        background: rgba(255, 255, 255, 0.98);
        overflow: hidden;
        
        .v-note-op {
          border-bottom: 1px solid rgba(232, 232, 232, 0.8);
          background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        }
        
        // 确保分栏模式下的内容不会溢出
        .v-note-panel {
          overflow-x: auto;
          overflow-y: auto;
        }
      }
      
      ::v-deep .v-note-edit {
        padding: 20px;
        background: rgba(255, 255, 255, 0.98);
        
        .CodeMirror {
          font-size: 14px;
          line-height: 1.6;
        }
        
        // 限制编辑区域中图片的最大宽度
        img {
          max-width: 100% !important;
          height: auto !important;
          display: block;
          margin: 10px auto;
          border-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
      
      ::v-deep .v-note-show {
        padding: 20px;
        background: rgba(255, 255, 255, 0.98);
        
        // 限制图片最大宽度，防止撑宽编辑器
        img {
          max-width: 100% !important;
          height: auto !important;
          display: block;
          margin: 10px auto;
          border-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        // 确保表格中的图片也不会溢出
        table img {
          max-width: 200px !important;
        }
      }
    }
  }
  
  .welcome-screen {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .welcome-content {
      text-align: center;
      
      .welcome-icon {
        font-size: 64px;
        color: #409eff;
        margin-bottom: 24px;
        display: block;
      }
      
      h2 {
        margin: 0 0 16px 0;
        color: #333;
      }
      
      p {
        margin: 0 0 24px 0;
        color: #666;
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .sidebar {
    width: 240px;
    
    &.collapsed {
      width: 0;
      border-right: none;
    }
  }
  
  .editor-toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    
    .toolbar-left {
      margin-right: 0;
      
      .title-input {
        max-width: none;
      }
    }
    
    .toolbar-right {
      justify-content: center;
    }
  }
}
</style>